import React, {Component} from "react";
import {connect} from "dva";
import time, {currentTime, dateFormat, getMockTime} from "@/utils/time";
import echarts from "echarts";
import {addResizeHook} from "@/utils/resize";
import {Row, DatePicker, Select, Col} from "antd";
import moment from "moment";
import {MEMBER_MAPPING_DICT} from '@/config/appConfig'
import {trigger} from "@/utils/utils";
import CustomDropdown from "./CustomDropdown"

const {RangePicker} = DatePicker;
const {Option} = Select;


class CoreData extends Component {

  colors = ['#5793f3', '#d14a61', '#675bba', '#3298DB', '#FFB980', '#2EC7C9', '#E5CF0D', '#8D98B3', '#73A373']

  stopLoop = false;

  state = {
    chart: null,
    startTime: time.getStartOfDay(),
    endTime: time.getEndOfDay(),
    globalTime: {
      currentTime: null
    },
    selectedParams: localStorage.getItem("selectedParams") ? JSON.parse(localStorage.getItem("selectedParams")) : [
      'CG_LT_GL_GL04_TQXZS',
      'CG_LT_GL_GL04_FYLL',
      'CG_LT_GL_GL04_ZXQL',
      'CG_LT_GL_GL04_RFWD',
      'CG_LT_GL_GL04_LFLL',
      'CG_LT_GL_GL04_FCokeRate',
      'CG_LT_GL_GL04_FCoalRate',
      'CG_LT_GL_GL04_XBYCZB',
      'CG_LT_GL_GL04_SBYCZB'
    ],

    // timeBetween: [time.getStartOfDay(), time.getEndOfDay()],
    current: this,
    option: {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      grid: {
        left: '2.5%',
        right: '50%',
        bottom: '16%'
      },
      legend: {
        data: ['透气性指数', '富氧流量', 'T阀座温度/T顶温', '热风温度', '冷风流量', '焦比', '煤比', '下部压差占比', '上部压差占比']
      },
      xAxis: {
        type: 'category',
        splitLine: {
          show: false
        },
        data: []
      },
      yAxis: [
        {
          type: 'value',
          name: '透气性指数',
          // min: 5,
          // max: 60,
          position: 'right',
          axisLine: {
            lineStyle: {
              // color: this.colors[0]
            }
          },
          axisLabel: {
            formatter: '{value}'
          }
        },
        {
          type: 'value',
          name: '富氧流量',
          // min: 2000,
          // max: 19000,
          position: 'right',
          offset: 65,
          splitLine: {show: false},
          axisLine: {
            lineStyle: {
              // color: this.colors[1]
            }
          },
          axisLabel: {
            formatter: '{value}'
          }
        },
        {
          type: 'value',
          name: '阀座温度/顶温',
          // min: 0,
          // max: 80,
          offset: 130,
          splitLine: {show: false},
          position: 'right',
          axisLine: {
            lineStyle: {
              // color: this.colors[2]
            }
          },
          axisLabel: {
            formatter: '{value}'
          }
        },
        {
          type: 'value',
          name: '热风温度',
          position: 'right',
          offset: 195,
          // min: 0,
          // max: 1200,
          splitLine: {show: false},
          axisLine: {
            lineStyle: {
              // color: this.colors[3]
            }
          },
          axisLabel: {
            formatter: '{value}'
          }
        },
        {
          type: 'value',
          name: '冷风流量',
          // min: 4000,
          // max: 7500,
          position: 'right',
          offset: 260,
          splitLine: {show: false},
          axisLine: {
            lineStyle: {
              // color: this.colors[4]
            }
          },
          axisLabel: {
            formatter: '{value}'
          }
        },
        {
          type: 'value',
          name: '焦比',
          // min: 0,
          // max: 2000,
          position: 'right',
          offset: 325,
          splitLine: {show: false},
          axisLine: {
            lineStyle: {
              // color: this.colors[5]
            }
          },
          axisLabel: {
            formatter: '{value}'
          }
        },
        {
          type: 'value',
          name: '煤比',
          // min: 0,
          // max: 1000,
          position: 'right',
          offset: 390,
          splitLine: {show: false},
          axisLine: {
            lineStyle: {
              // color: this.colors[6]
            }
          },
          axisLabel: {
            formatter: '{value}'
          }
        },
        {
          type: 'value',
          name: '下部压差占比',
          // min: 0,
          // max: 80,
          position: 'right',
          offset: 455,
          splitLine: {show: false},
          axisLine: {
            lineStyle: {
              // color: this.colors[7]
            }
          },
          axisLabel: {
            formatter: '{value}'
          }
        },
        {
          type: 'value',
          name: '上部压差占比',
          // min: 0,
          // max: 18,
          position: 'right',
          offset: 540,
          splitLine: {show: false},
          axisLine: {
            lineStyle: {
              // color: this.colors[8]
            }
          },
          axisLabel: {
            formatter: '{value}'
          }
        }
      ],
      series: []
    }
  };

  selectRef=el=> {
    el.click()
  }

  async componentDidMount() {
    const {option} = this.state

    const payload = await getMockTime("GaoLu")
    this.setState({startTime:payload.start,endTime:payload.end})

    this.coreDataReq = requestAnimationFrame(() =>
      trigger(
        () => {
          // 发送API 请求
          this.getCoreData();
        },
        new Date().valueOf(),
        10 * 1000,
        true,
        () => this.stopLoop));

    // 基于准备好的dom，初始化echarts实例
    this.state.chart = echarts.init(document.getElementById("coreData"));
    // 绘制图表
    this.state.chart.setOption(this.state.option);

    this.state.chart.on('legendselectchanged', this.suppressSelection);

    addResizeHook(this, () => {
      if (this.chartRef) {
        this.state.offset = this.getYxisOffset();
        this.dynamicSetOption(this.state.selectedParams, option, null);
        this.state.chart.setOption(option, true);
        this.state.chart.resize()
      }
    }, true, -1);

  }

  componentWillUnmount() {
    cancelAnimationFrame(this.coreDataReq);
    this.stopLoop = true
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    const {coreData, globalTime, hasParent} = nextProps;
    const {option, selectedParams, chart, current} = prevState;
    if (coreData !== undefined && coreData !== null && prevState.chart !== null) {
      option.xAxis.data = coreData.DateTime;
      current.dynamicSetOption(selectedParams, option, null, true);
      selectedParams.forEach((key, index) => {
        option.series[index].data = coreData[key];
      });
      chart.setOption(option, true);
    }
    // if (globalTime && hasParent && prevState.globalTime.currentTime !== globalTime.currentTime) {
    //   return {
    //     startTime: new Date(globalTime.currentTime.valueOf() - 24 * 60 * 60 * 1000),
    //     endTime: globalTime.currentTime,
    //     globalTime: {
    //       currentTime: globalTime.currentTime
    //     }
    //   }
    // }
    // state 不需要更改
    return null
  }

  timePick = value => {
    this.state.startTime = value[0].toDate();
    this.state.endTime = value[1].toDate();
    this.getCoreData()
  };

  getCoreData = () => {
    const payload = {
      start: dateFormat(this.state.startTime),
      end: dateFormat(this.state.endTime),
      params: this.state.selectedParams
    };
    this.props.dispatch({
      type: 'gaolu/getCoreDataEffect',
      payload
    });
  };

  /**
   * 获取y轴偏移量
   * @returns {number}
   */
  getYxisOffset = () => {
    const divWidth = this.chartRef.offsetWidth;
    const right = divWidth * 0.5;
    const offset = Math.min(right / (this.state.selectedParams.length + 1), 65);
    return offset
  };

  /**
   * 动态调整图样
   * @param keys
   * @param option
   * @param newSelectedParams
   * @param reloadData
   */
  dynamicSetOption = (keys, option, newSelectedParams, reloadData = false) => {
    option.legend.data = [];
    option.yAxis = [];
    if (reloadData) option.series = [];
    keys.forEach((key, index) => {
      const desc = MEMBER_MAPPING_DICT[key];
      const {offset} = this.state;
      const splitLineShow = index === 0;

      if (newSelectedParams) {
        newSelectedParams.push(key);
      }
      option.legend.data.push(desc);
      option.legend.selected = JSON.parse(localStorage.getItem("legendSelected"));
      option.yAxis.push({
        type: 'value',
        name: desc,
        offset: index * offset,
        position: 'right',
        splitLine: {show: splitLineShow},
        axisLabel: {
          formatter: '{value}'
        }
      });
      if (reloadData) {
        option.series.push({
          name: desc,
          type: 'line',
          yAxisIndex: index,
          data: []
        })
      }
    });
  };

  handleParamChange = keys => {
    const {option} = this.state;
    const selectedParams = [];
    this.state.offset = this.getYxisOffset();
    this.dynamicSetOption(keys, option, selectedParams);


    this.state.selectedParams = selectedParams;
    this.state.option = option;

    localStorage.setItem("selectedParams", JSON.stringify(selectedParams));
    this.getCoreData();
  };

  suppressSelection = params => {
    const legendSelected = params.selected;
    localStorage.setItem("legendSelected", JSON.stringify(legendSelected))

  };


  render() {
    const {
      width = 100,
      height = 500
    }
      = this.props;

    const {startTime, endTime} = this.state;
    const dateFormat = 'YYYY-MM-DD HH';

    return (

      <div>
        <Row>
          <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
            <RangePicker
              key={Math.random()}
              showTime={{format: 'HH'}}
              format={dateFormat}
              placeholder={['开始时间', '结束时间']}
              onOk={this.timePick}
              style={{width: 300}}
              defaultValue={[moment(startTime, dateFormat), moment(endTime, dateFormat)]}
            />
          </Col>
          <Col xs={24} sm={24} md={10} lg={11} xl={10} xxl={6} style={{paddingLeft: 20}}>
            {/*<Select*/}
            {/*  style={{width: '100%'}}*/}
            {/*  // ref={this.selectRef}*/}
            {/*  mode="multiple"*/}
            {/*  placeholder="参数选择"*/}
            {/*  onChange={this.handleParamChange}*/}
            {/*  defaultValue={this.state.selectedParams}*/}
            {/*>*/}
            {/*  {*/}
            {/*    Object.entries(MEMBER_MAPPING_DICT).map(([key, desc]) => {*/}
            {/*      return <Option value={key}>{desc}</Option>*/}
            {/*    })*/}
            {/*  }*/}
            {/*</Select>*/}
            <CustomDropdown sectList={
              Object.entries(MEMBER_MAPPING_DICT).map(([key, desc]) => ({title:desc,id:key}))
            }
                            onChange={this.handleParamChange} selectedKeys={this.state.selectedParams}/>
          </Col>
        </Row>
        <Row>
          <div id="coreData" ref={ref => this.chartRef = ref} style={{width: `${width}%`, height}}/>
        </Row>
      </div>
    )
  }
}


export default connect(({gaolu, global}) => ({
  coreData: gaolu.coreData,
  globalTime: gaolu.globalTime,
  global
}))(CoreData);
